"use strict";

const BaseController = require("./base");

class UserController extends BaseController {
  // 发送邮箱验证码
  async sendcode() {
    const { ctx } = this;
    const email = ctx.query.email;
    const code = Math.random().toString().slice(2, 6);
    const title = "博客验证码";
    const html = `
		<h1>博客验证码是${code}</h1>
		`;
    console.log("邮件" + email + "验证码是" + code);
    const hasSend = await this.service.tools.sendEmail(email, title, html);
    console.log(hasSend);
    if (hasSend) {
      ctx.session.emailcode = code;
      this.message("发送成功");
    } else {
      this.error("发送失败");
    }
  }

  // 获取图片验证码接口
  async captcha() {
    const { ctx } = this;
    const captcha = await this.service.tools.captcha();
    ctx.response.type = "image/svg+xml";
    ctx.session.captcha = captcha.text;
    console.log("图片验证码是" + captcha.text);
    ctx.body = captcha.data;
  }

  // 注册
  /*
  async register() {
    const { ctx } = this;
    let { email, emailcode, captcha, nickname, password } = ctx.request.body;
    console.log(emailcode, ctx.session.emailcode);
    if (emailcode !== ctx.session.emailcode) {
      return this.error("邮箱验证码错误");
    }
    if (captcha.toUpperCase() !== ctx.session.captcha.toUpperCase()) {
      return this.error("图片验证码错误");
    }
    if (await this.checkEmail(email)) {
      return this.error("邮箱一已经存在");
    }
    let res = await ctx.model.User.create({
      email,
      nickname,
      password,
    });
    if (res._id) {
      this.success("注册成功");
    }
  }
  * */
  async register() {
    const { ctx } = this;
    let { nickname, password, avatar } = ctx.request.body;
    if (await this.ctx.model.User.findOne({ nickname })) {
      return this.error("用户名已经存在");
    }
    let res = await ctx.model.User.create({
      nickname,
      password,
      avatar,
    });
    if (res._id) {
      this.success("注册成功");
    }
  }

  // 检查邮箱
  async checkEmail(email) {
    const user = await this.ctx.model.User.findOne({ email });
    return user;
  }

  // 登录逻辑
  /*
  async login() {
    //   jwt
    const { ctx, app } = this;
    const { email, password } = ctx.request.body;
    let user = await ctx.model.User.findOne({
      email,
      password,
    });
    if (user) {
      const { nickname } = user;
      const token = app.jwt.sign(
        {
          nickname,
          email,
          id: user._id,
        },
        app.config.jwt.secret,
        {
          //   expiresIn: "60s",
          expiresIn: "1h",
        }
      );
      this.success({ token, email });
    } else {
      this.error("用户名或者密码错误");
    }
  }
  * */
  async login() {
    //   jwt
    const { ctx, app } = this;
    const { nickname, password } = ctx.request.body;
    let user = await ctx.model.User.findOne({ nickname, password });
    if (user) {
      const token = app.jwt.sign(
        {
          id: user._id,
        },
        app.config.jwt.secret,
        {
          //   expiresIn: "60s",
          expiresIn: "24h",
        }
      );
      this.success({ token });
    } else {
      this.error("用户名或者密码错误");
    }
  }

  // 获取用户信息
  /*
   async detail() {
    const { ctx } = this;
    const userId = ctx.state.userId;
    // const user = await ctx.model.User.findById(userId);
    const user = await this.checkEmail(ctx.state.email);
    this.success(user);
  }
  * */
  async detail() {
    const { ctx } = this;
    const userId = ctx.state.userId;
    const user = await ctx.model.User.findById(userId);
    this.success(user);
  }

  // 判断用户是否被关注
  async isFollow() {
    let { ctx } = this;
    let me = await ctx.model.User.findById(ctx.state.userId);
    // !! 是可以转化为布尔值
    let isFollow = !!me.following.find((id) => id.toString() == ctx.params.id);
    this.success({ isFollow });
  }

  // 关注用户
  async follow() {
    let { ctx } = this;
    let me = await ctx.model.User.findById(ctx.state.userId);
    let isFollow = !!me.following.find((id) => id.toString() == ctx.params.id);
    if (!isFollow) {
      me.following.push(ctx.params.id);
      me.save();
      this.success("关注成功！");
    }
  }
  // 取消关注用户
  async cancelFollow() {
    let { ctx } = this;
    let me = await ctx.model.User.findById(ctx.state.userId);
    let index = me.following.findIndex((id) => id.toString() == ctx.params.id);
    if (index > -1) {
      me.following.splice(index, 1);
      me.save();
      this.message("取消关注成功");
    }
  }

  // 关注的人
  async following() {
    let { ctx } = this;
    let users = await ctx.model.User.findById(ctx.params.id).populate(
      "following"
    );
    this.success(users.following);
  }

  // 粉丝
  async follows() {
    let { ctx } = this;
    let users = await ctx.model.User.find({ following: ctx.params.id });
    this.success(users);
  }

  async likeArticle() {
    let { ctx } = this;
    let me = await ctx.model.User.findById(ctx.state.userId);
    if (!me.likeArticles.find((id) => id.toString() == ctx.params.id)) {
      me.likeArticles.push(ctx.params.id);
      me.save();
      await ctx.model.Article.findByIdAndUpdate(ctx.params.id, {
        $inc: { like: 1 },
      }); //
      return this.message("点赞成功！");
    }
  }
  async cancellikeArticle() {
    let { ctx } = this;
    let me = await ctx.model.User.findById(ctx.state.userId);
    let index = me.likeArticles.findIndex(
      (id) => id.toString() == ctx.params.id
    );
    if (index > -1) {
      me.likeArticles.splice(index, 1);
      me.save();
      await ctx.model.Article.findByIdAndUpdate(ctx.params.id, {
        $inc: { like: -1 },
      }); //
      return this.message("已取消点赞！");
    }
  }

  async getUserLikeArticles() {
    let { ctx } = this;
    let user = await ctx.model.User.findById(ctx.params.id).populate(
      "likeArticles"
    );
    let arr = [];
    let promise = new Promise((resolve) => {
      user.likeArticles.forEach(async (item) => {
        let res = await ctx.model.Article.findById(item._id)
          .populate("author")
          .populate("category");
        console.log(res, "res");
        arr.push(res);
        console.log(arr, "arr");
      });
    });
    promise.then(() => {
      console.log(arr, "21333333333333333333333333333");
    });
    this.success(user.likeArticles);
  }

  async getUserInfoById() {
    const { ctx } = this;
    let user = await ctx.model.User.findById(ctx.params.id).populate(
      "likeArticles"
    );
    this.success(user);
  }
}

module.exports = UserController;
